package com.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.dao.BaseDao;
import com.db.DBManager;

public class BaseDaoImpl implements BaseDao {

	@Override
	public boolean addData(String url) {
		try {
			Connection conn = DBManager.getConn();
			PreparedStatement ps = conn.prepareStatement(url);
			ps.execute();
			DBManager.close(null, ps, conn);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public int addData(String url, String sql) {
		int id = 0;
		try {
			Connection conn = DBManager.getConn();
			PreparedStatement ps = conn.prepareStatement(url);
			ps.execute();
			ResultSet result = ps.executeQuery(sql);
			if (result.next()) {
				id = result.getInt(1);
			}
			DBManager.close(null, ps, conn);
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
		return id;
	}

	@Override
	public boolean delData(String sql) {
		try {
			Connection conn = DBManager.getConn();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.execute();
			DBManager.close(null, ps, conn);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean modData(String sql) throws SQLException {
		boolean flag = false;
		int result = 0;
		try {
			Connection conn = DBManager.getConn();
			PreparedStatement ps = conn.prepareStatement(sql);
			result = ps.executeUpdate();
			if (result > 0) {
				flag = true;
			}
			DBManager.close(null, ps, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	@Override
	public Object queData(String url) {
		ResultSet result = null;
		try {
			Connection conn = DBManager.getConn();
			PreparedStatement ps = conn.prepareStatement(url);
			result = ps.executeQuery();
			if (result.next()) {
				System.out.println("result:" + result);
			}
			DBManager.close(null, ps, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public boolean verData(String url) {
		boolean flag = false;
		ResultSet result = null;
		try {
			Connection conn = DBManager.getConn();
			PreparedStatement ps = conn.prepareStatement(url);
			result = ps.executeQuery();
			if (result.next()) {
				flag = true;
			}
			DBManager.close(result, ps, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	public String queryData(String url) {
		ResultSet result = null;
		String count = "";
		try {
			Connection conn = DBManager.getConn();
			PreparedStatement ps = conn.prepareStatement(url);
			result = ps.executeQuery();
			if (result.next()) {
				count = result.getString(1);
			}
			DBManager.close(null, ps, conn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}

}
